<template>
  <div class="body">
    <div class="table_filtrate">
      <div class="tf_item">
        <div class="tag">交易类型</div>
        <el-radio-group v-model="tableParams.trade_type" size="mini">
          <el-radio-button label="all">全部</el-radio-button>
          <el-radio-button label="recharge">充值</el-radio-button>
          <el-radio-button label="replenish">补款</el-radio-button>
          <el-radio-button label="expense">退款</el-radio-button>
        </el-radio-group>
      </div>
      <div class="tf_item">
        <div class="tag">审核状态</div>
        <el-radio-group v-model="tableParams.status" size="mini">
          <el-radio-button label="all">全部</el-radio-button>
          <el-radio-button label="await">待审核</el-radio-button>
          <el-radio-button label="approve">通过</el-radio-button>
          <el-radio-button label="refuse">驳回</el-radio-button>
        </el-radio-group>
      </div>

      <div class="tf_item" style="margin-right: 30px">
        <div class="tag">商务</div>
        <!-- <el-input v-model="tableParams.initiator_uid" class="input_fuzzy_search input" size="mini" placeholder="ID|名字" clearable /> -->
          <el-select v-model="tableParams.initiator_uid" class="input" placeholder="请选择" size="mini">
            <el-option label="全部" :value="0" />
            <el-option v-for="item in tableFiltrateData.business_list" :key="item.id" :label="item.nickname"
              :value="item.id">
              <span style="float: left">{{ item.nickname }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.group_name
              }}</span>
            </el-option>
          </el-select>
      </div>

      <div class="tf_item" style="margin-right: 30px">
        <div class="tag">机构ID</div>
        <el-input v-model="tableParams.o_id" class="input_fuzzy_search input" size="mini" placeholder="ID|名字"
          clearable />
      </div>

      <div class="tf_item" style="margin-right: 30px">
        <el-date-picker v-model="tableParams.time_interval" size="mini" type="daterange" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" value-format="timestamp" />
      </div>


      <div class="tf_item">
        <el-button @click="loadTableData" type="primary" plain size="mini">搜索</el-button>
      </div>
    </div>

    <div class="table-card">
      <el-table v-loading="table_loading" :data="tableData.data" :border="true" size="mini" show-summary
        :summary-method="summaryAmount">
        <el-table-column prop="id" label="ID" width="80" align="center">
        </el-table-column>

        <el-table-column label="提审人" align="center">
          <template slot-scope="scope">
            <div>{{ scope.row.initiator.nickname }}</div>
          </template>
        </el-table-column>

        <el-table-column label="机构名字" align="center" width="200">
          <template slot-scope="scope">
            <div>{{ scope.row.organization.name }}</div>
          </template>
        </el-table-column>

        <el-table-column label="类型" width="100" align="center">
          <template slot-scope="scope">
            <el-tag v-if="
              scope.row.transaction_type == 'recharge' &&
              scope.row.recharge_type == 'receipts'
            " type="success" effect="plain">充值</el-tag>
            <el-tag v-else-if="
              scope.row.transaction_type == 'recharge' &&
              scope.row.recharge_type == 'replenish'
            " type="success" effect="plain">补款</el-tag>
            <el-tag v-else-if="scope.row.transaction_type == 'expense'" type="danger" effect="plain">退款</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="金额" align="center" width="120" prop="money">
          <template slot-scope="scope">
            <p v-if="scope.row.transaction_type == 'recharge'" style="color: #67c23a">
              +{{ scope.row.money }}
            </p>
            <p v-else-if="scope.row.transaction_type == 'expense'" style="color: #f56c6c">
              -{{ scope.row.money }}
            </p>
          </template>
        </el-table-column>

        <el-table-column label="凭证" width="90">
          <template slot-scope="scope">
            <el-image v-for="img in scope.row.voucher_img" style="width: 30px; height: 30px" :key="img" :src="img"
              fit="cover" @click="goToUrl(img)"></el-image>
          </template>
        </el-table-column>

        <el-table-column label="备注">
          <template slot-scope="scope">
            <div class="text_line">{{ scope.row.remark }}</div>
          </template>
        </el-table-column>

        <el-table-column label="操作人" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.auditor">
              {{ scope.row.auditor.nickname }}
            </div>
          </template>
        </el-table-column>
        <!--
        <el-table-column prop="createtime" label="提审日期" width="140">
        </el-table-column> -->

        <el-table-column prop="status_updatetime" label="日期" align="center" width="220">
          <template slot-scope="scope">
            <div style="margin-bottom: 10px; color: #607d8b; text-align: left">
              <span>提审日期:</span>
              <span> {{ scope.row.createtime }} </span>
            </div>
            <div style="color: #009688; text-align: left">
              <span> 操作日期: </span>
              <span>
                {{
                  scope.row.status_updatetime
                    ? scope.row.status_updatetime
                    : "等待操作"
                }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status == 'approve'" type="success" plain>通过</el-tag>
            <el-tag v-else-if="scope.row.status == 'refuse'" type="info" plain>拒绝</el-tag>
            <el-tag v-else-if="scope.row.status == 'await'" type="warning" plain>待审核</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" v-if="jsAuthJudgment(['manage', 'business'])">
          <template slot-scope="scope">
            <el-link class="handle" type="primary" v-if="scope.row.status == 'await'"
              @click="handleTableEdit(scope.$index, scope.row, 'approve')">通过</el-link>
            <el-link class="handle" type="danger" v-if="scope.row.status == 'await'"
              @click="handleTableEdit(scope.$index, scope.row, 'refuse')">拒绝</el-link>

            <el-link class="handle" disabled v-if="scope.row.status != 'await'">已操作</el-link>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination class="pagination" @size-change="handleTableSizeChange" @current-change="handleTableCurrentChange"
        :current-page="currentPage4" :page-sizes="$pageSize" :page-size="tableParams.size"
        layout="total, sizes, prev, pager, next, jumper" :total="tableData.total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { oblistpage, obreply } from "@/api/apiFinance";
import {
  getUploadingImgUrl,
  getUploadingVideoUrl,
  getImgUrl,
} from "@/api/uploading";
import { dateToTimestamp } from '@/utils/datetimeUtil'
import { arrayToString, stringToArray } from "@/utils/arrayUtil";
import { formatTimestamp } from "@/utils/datetimeUtil";
import { appUtil, authJudgment } from "@/utils/appUtil";
import { apiAgentList } from '@/api/apiCommon';
export default {
  name: "Index",
  data() {
    return {
      tableParams: {
        page: 1,
        size: 15,
        status: "all",
        trade_type: "all",
        initiator_uid: "",
        o_id: "",
        time_interval: [
          new Date(new Date().setHours(0, 0, 0, 0)), // 今天的初始时间戳
          new Date(new Date().setHours(23, 59, 59, 999)), // 今天的结束时间戳
        ],
      },
      tableFiltrateData: {
        business_list: []
      },
      tableData: {
        current_page: 1,
        data: [],
        last_page: 1,
        per_page: "15",
        total: 0,
      },
      currentPage4: 1,
      group: [],
      dialogConfig: {
        title: "添加人员",
      },
      table_loading: false,
      dialogFormVisible: false,
      fromViewCofing: {
        input_width: "120px",
        label_width: "120px",
      },
    };
  },
  created() {
    debugger;
    if (this.jsAuthJudgment('manage')) {
      this.req_agent()
    }
    this.loadTableData();
  },
  methods: {
    // 获取商务人员
    req_agent() {
      const _this = this
      apiAgentList({
        page: 1,
        size: 99,
        status: 'normal',
        group_id: '2,3,5'
      })
        .then((response) => {
          const result = response.data.datalist.data
          _this.tableFiltrateData.business_list = result
        })
        .catch(function (result) {
          _this.$message.error(result.msg)
        })
    },
    goToUrl(url) {
      window.open(url, '_blank')
    },
    //图片展示
    imgShow(url) {
      return getImgUrl(url);
    },
    // 权限判断
    jsAuthJudgment(agree_group) {
      return authJudgment(agree_group);
    },
    // 列表请求
    loadTableData() {
      const _this = this;
      _this.table_loading = true;

      var tableParamsData = { ..._this.tableParams }
      if (tableParamsData.fuzzy_search == "") {
        delete tableParamsData.fuzzy_search;
      }
      if (tableParamsData.group_id == 0) {
        delete tableParamsData.group_id;
      }
      if (tableParamsData.initiator_uid == "") {
        delete tableParamsData.initiator_uid;
      }
      if (tableParamsData.o_id == "") {
        delete tableParamsData.o_id;
      }

      var start_date = tableParamsData['time_interval'][0]
      var end_date = tableParamsData['time_interval'][1]
      tableParamsData['start_time'] = dateToTimestamp(start_date)
      tableParamsData['end_time'] = dateToTimestamp(end_date)
      delete tableParamsData['time_interval']
      oblistpage(tableParamsData)
        .then((response) => {
          const result = response;
          var tableData = result.data.datalist;
          _this.tableData = [];
          for (var i = 0; i < tableData.data.length; i++) {
            var imgArray = stringToArray(tableData.data[i]["voucher_img"]);
            for (var j = 0; j < imgArray.length; j++) {
              imgArray[j] = getImgUrl(imgArray[j]);
            }
            tableData.data[i]["voucher_img"] = imgArray;
            tableData.data[i]["createtime"] = formatTimestamp(
              tableData.data[i]["createtime"],
              "YYYY-MM-DD HH:mm:ss"
            );
            if (tableData.data[i]["status_updatetime"]) {
              tableData.data[i]["status_updatetime"] = formatTimestamp(
                tableData.data[i]["status_updatetime"],
                "YYYY-MM-DD HH:mm:ss"
              );
            }
          }
          _this.tableData = tableData;
          _this.table_loading = false;
        })
        .catch(function (result) {
          _this.$message.error(result.msg);
          _this.table_loading = false;
          _this.tableData.data = null;
        });
    },
    // 初始化表单数据
    from_init() {
      this.form = {
        id: 0,
        account: "",
        password: "",
        password_confirmation: "",
        mobile: "",
        nickname: "",
        group_id: "",
        status: "normal",
      };
    },
    // 表格操作
    handleTableEdit(index, row, status) {
      var title = "";
      if (status == "approve") {
        title = "是否通过该笔交易?";
      } else if (status == "refuse") {
        title = "是否拒绝该笔交易";
      }

      this.$confirm(title, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var params = {
            id: row.id,
            status: status,
          };
          const _this = this;
          const loading = this.$loading({
            lock: true,
            text: "Loading",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          obreply(params).then((response) => {
            _this.$message({
              message: response.msg,
              type: "success",
            });
            loading.close();
            _this.loadTableData();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
          loading.close();
        });
    },

    // 数量改变
    handleTableSizeChange(val) {
      this.tableParams.size = val;
      this.loadTableData();
    },
    // 页数改变
    handleTableCurrentChange(val) {
      this.tableParams.page = val;
      this.loadTableData();
    },
    // 金额列求和方法
    summaryAmount(param) {
      const { columns, data } = param;
      const sums = [];

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'; // 第一列显示“合计”
          return;
        }

        // 判断是否是金额列
        if (column.property === 'money') {
          let total = 0;

          data.forEach(item => {
            const money = Number(item.money);
            if (isNaN(money)) return;

            if (item.transaction_type === 'recharge') {
              total += money; // 充值 + 金额
            } else if (item.transaction_type === 'expense') {
              total -= money; // 退款 - 金额
            }
          });

          sums[index] = total.toFixed(2); // 显示带符号的金额
        } else {
          sums[index] = ''; // 非金额列留空
        }
      });

      return sums;
    }
  },
};
</script>

<style lang="scss">
// .body {
//   padding: 5px;
//   background-color: #f5f5f5;

//   .table_operate {
//     background-color: #fff;

//     .btn_add {
//       margin-top: 12px;
//       margin-bottom: 12px;
//       margin-left: 12px;
//     }
//   }

//   .table_filtrate {
//     margin-bottom: 10px;
//     display: flex;
//     background-color: #fff;
//     padding: 20px;
//     align-items: center;
//     border-radius: 12px;

//     .tag {
//       font-size: 12px;
//       color: #424242;
//       padding-right: 10px;
//     }

//     .input {
//       padding-right: 30px;
//     }

//     .input_fuzzy_search {
//       width: 230px;
//       margin-right: 10px;
//     }
//   }
// }</style>
